const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
  console.log(event)
  let wxContext = cloud.getWXContext()
  const target_db = db.collection(event.collection)
  if (event.data) {
    if (typeof event.data == 'string') {
      //将传入字符串转换成正常对象
      console.log(event.data)
      event.data = eval('(' + event.data + ')');
    }
  }
  try {
    if (event.type == 'insert') {
      return await target_db.add({
        data: {
          ...event.data
        }
      })
    } else if (event.type == 'update_user') {
      return await target_db.where({
        openid: wxContext.OPENID
      }).update({
        data: {
          ...event.data
        }
      })
    } else if (event.type == 'delete') {
      return await target_db.where({
        ...event.is_where
      }).remove()
    } else if (event.type == 'get_rank_list') {
      return await target_db.where({
          update_time: db.command.lte(event.after_day).and(db.command.gte(event.is_day))
        })
        .orderBy('score', 'desc')
        .skip(20 * event.skip)
        .limit(event.limit)
        .get()
    } else if (event.type == 'get_list') {
      return await target_db.where({
          ...event.is_where
        })
        .orderBy(event.sort, event.sort_category)
        .skip(20 * event.skip)
        .limit(event.limit)
        .get()
    } else if (event.type == 'get_detail') {
      return await target_db.where({
        ...event.is_where
      }).get()
    } else if (event.type == 'update_detail') {
      return await target_db.where({
        ...event.is_where
      }).update({
        data: {
          ...event.data
        }
      })
    }
  } catch (e) {
    console.log(e)
  }
}